﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;
using EffiProz.Core.Results;
using EffiProz.Core.Navigators;
using EffiProz.Core.Rights;

namespace EffiProz.Core
{
    public class RoutineSchema : SchemaObject
    {
        public Routine[] routines = Routine.emptyArray;
        public int routineType;
        private QNameManager.QName name;

        public RoutineSchema(int type, QNameManager.QName name)
        {
            routineType = type;
            this.name = name;
        }

        public virtual int getType()
        {
            return routineType;
        }

        public virtual QNameManager.QName getCatalogName()
        {
            return name.schema.schema;
        }

        public virtual QNameManager.QName getSchemaName()
        {
            return name.schema;
        }

        public virtual QNameManager.QName getName()
        {
            return name;
        }

        public virtual Grantee getOwner()
        {
            return name.schema.owner;
        }

        public virtual OrderedHashSet getReferences()
        {

            OrderedHashSet set = new OrderedHashSet();

            for (int i = 0; i < routines.Length; i++)
            {
                set.addAll(routines[i].getReferences());
            }

            return set;
        }

        public virtual OrderedHashSet getComponents()
        {

            OrderedHashSet set = new OrderedHashSet();

            set.addAll(routines);

            return set;
        }

        public virtual void compile(Session session, SchemaObject parentObject) { }

        public virtual String getSQL()
        {
            return null;
        }

        public String[] getSQLArray()
        {

            EfzArrayList list = new EfzArrayList();

            for (int i = 0; i < routines.Length; i++)
            {
                list.add(routines[i].getSQL());
            }

            String[] array = new String[list.size()];

            list.toArray(array);

            return array;
        }

        public void addSpecificRoutine(Database database, Routine routine)
        {

            int signature = routine.getParameterSignature();
            SqlType[] types = routine.getParameterTypes();

            for (int i = 0; i < this.routines.Length; i++)
            {
                if (routines[i].parameterTypes.Length == types.Length)
                {
                    if (routineType == SchemaObjectTypes.PROCEDURE)
                    {
                        throw Error.error(ErrorCode.X_42605);
                    }

                    bool match = true;

                    for (int j = 0; j < types.Length; j++)
                    {
                        if (!routines[i].parameterTypes[j].Equals(types[j]))
                        {
                            match = false;

                            break;
                        }
                    }

                    if (match)
                    {
                        throw Error.error(ErrorCode.X_42605);
                    }
                }
            }

            if (routine.getSpecificName() == null)
            {
                QNameManager.QName specificName =
                    database.nameManager.newSpecificRoutineName(name);

                routine.setSpecificName(specificName);
            }
            else
            {
                routine.getSpecificName().parent = name;
                routine.getSpecificName().schema = name.schema;
            }
            routine.setName(name);

            routine.routineSchema = this;
            routines = (Routine[])ArrayUtil.resizeArray(routines,
                    routines.Length + 1);
            routines[routines.Length - 1] = routine;
        }

        public void removeSpecificRoutine(Routine routine)
        {

            for (int i = 0; i < this.routines.Length; i++)
            {
                if (routines[i] == routine)
                {
                    routines = (Routine[])ArrayUtil.toAdjustedArray(routines,
                            null, i, -1);

                    break;
                }
            }
        }

        public Routine[] getSpecificRoutines()
        {
            return routines;
        }

        public Routine getSpecificRoutine(SqlType[] types)
        {

            int matchIndex = -1;


            for (int i = 0; i < this.routines.Length; i++)
            {
                int matchCount = 0;

                if (routines[i].parameterTypes.Length != types.Length)
                {
                    continue;
                }

                if (types.Length == 0)
                {
                    return this.routines[i];
                }

                for (int j = 0; j < types.Length; j++)
                {
                    int typeDifference;

                    // parameters
                    if (types[j] == null)
                    {
                        continue;
                    }

                    typeDifference =
                        types[j].precedenceDegree(routines[i].parameterTypes[j]);

                    if (typeDifference < 0)
                    {
                        goto outerLoop; // continue outer loop
                    }
                    else if (typeDifference == 0)
                    {
                        if (matchCount == j)
                        {
                            matchCount = j + 1;
                        }
                    }
                }

                if (matchCount == types.Length)
                {
                    return routines[i];
                }

                if (matchIndex == -1)
                {
                    matchIndex = i;

                    continue;
                }

                for (int j = 0; j < types.Length; j++)
                {
                    if (types[j] == null)
                    {
                        continue;
                    }

                    int oldDiff = types[j].precedenceDegree(
                        routines[matchIndex].parameterTypes[j]);
                    int newDiff =
                        types[j].precedenceDegree(routines[i].parameterTypes[j]);

                    if (oldDiff == newDiff)
                    {
                        continue;
                    }

                    if (newDiff < oldDiff)
                    {
                        matchIndex = i;
                    }

                    goto outerLoop;                       
                }

            outerLoop:
                continue;
            }

            if (matchIndex < 0)
            {
                throw Error.error(ErrorCode.X_42501);
            }

            return routines[matchIndex];
        }

        public Routine getSpecificRoutine(int paramCount)
        {

            for (int i = 0; i < this.routines.Length; i++)
            {
                if (routines[i].parameterTypes.Length == paramCount)
                {
                    return routines[i];
                }
            }

            throw Error.error(ErrorCode.X_42501);
        }
    }
}
